//
//  JKNetworking.m
//  JKRecover
//
//  Created by Veer on 2018/7/13.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "JKNetworking.h"



@implementation JKNetworking


+ (NSString *)getSignWithDict:(NSDictionary *)dict
{
    
    NSArray *keyArray = dict.allKeys;
    NSArray *sorKeyArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(NSString   * _Nonnull obj1, NSString   * _Nonnull obj2) {
        
        return [obj1 compare:obj2];
    }];
    
    NSMutableString *signStr = [NSMutableString string];
    for (int i = 0; i < sorKeyArray.count; i++) {
        
        NSString *key = sorKeyArray[i];
        [signStr appendFormat:@"%@=%@&", key, dict[key]];
    }
    [signStr appendFormat:@"key=%@", Salt];;
    
    
    return signStr.md5;
}


+ (void)postWithSign:(NSString *)api parameters:(NSMutableDictionary *)param success:(void(^)(NSDictionary *responseObject))success error:(void(^)(NSError * _Nonnull error))erro
{
    
    NSMutableDictionary *mParam = [NSMutableDictionary dictionaryWithDictionary:param];
    
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    NSString *timeStampStr = [NSString stringWithFormat:@"%.0lf", timeStamp];
    mParam[@"timestamp"] = @"20180827211540";
    
    mParam[@"sign"] = [self getSignWithDict:[mParam copy]];
    
    
    [self post:api parameters:mParam success:success error:erro];
}


+ (void)post:(NSString *)api parameters:(NSMutableDictionary *)param success:(void(^)(NSDictionary *responseObject))success error:(void(^)(NSError * _Nonnull error))erro
{

    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
    
    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", @"text/html", nil];
    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;
    
    sessionMgr.requestSerializer=[AFHTTPRequestSerializer serializer];
    
    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionMgr.requestSerializer.timeoutInterval = 30.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", BaseUrl, api];
    if ([api hasPrefix:@"http"]) {
        urlStr = api;
    }
    
    [sessionMgr POST:urlStr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSInteger code = [responseObject[@"code"] integerValue];
        NSString *msg = responseObject[@"msg"];

        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error.code == -1009) {
            
            [SVProgressHUD showImage:nil status:@"亲，你似乎忘记连接网络了哦~"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
        }
        erro(error);
    }];
    
//    [sessionMgr.operationQueue cancelAllOperations];
}


+ (void)uploadImageWith:(NSString *)api parameters:(NSMutableDictionary *)param constructingBodyWithBlock:(void(^)(id<AFMultipartFormData>  _Nonnull formData))block success:(void(^)(NSDictionary *responseObject))success error:(void(^)(NSError * _Nonnull error))erro
{
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
    
    sessionMgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                            @"text/html",
                                                            @"text/plain",
                                                            @"image/jpeg",
                                                            @"image/png",
                                                            @"application/octet-stream",
                                                            @"text/json",
                                                            nil];
    
    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;

    sessionMgr.requestSerializer=[AFHTTPRequestSerializer serializer];
    
    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionMgr.requestSerializer.timeoutInterval = 60.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", BaseUrl, api];
    if ([api hasPrefix:@"http"]) {
        urlStr = api;
    }
    
    [sessionMgr POST:urlStr parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (block) {
            block(formData);
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == -1009) {
            
            [SVProgressHUD showImage:nil status:@"亲，你似乎忘记连接网络了哦~"];
        }else if (error.code == -1001){ // 链接超时
            
            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{
            
        }
        if (erro) {
            erro(error);
        }
    }];
}


@end
